<?php

namespace App\Controllers;

use Exception;

class User extends BaseController
{

    public function index(): \CodeIgniter\HTTP\ResponseInterface
    {
        $rules     = [
            "page"     => 'if_exist|is_natural_no_zero',
            "pageSize" => 'if_exist|less_than_equal_to[50]',
            "username" => 'if_exist|string',
            "mobile"   => 'if_exist|string',
            "orderBy"  => 'if_exist|permit_empty|in_list[username,login_time]',
        ];
        $errorsMsg = [
            'page'     => [
                'is_natural_no_zero' => '当前页数不能小于1',
            ],
            'pageSize' => [
                'less_than_equal_to' => '分页条数必须少于50',
            ],
            'username' => [
                'string' => '请输入用户名'
            ],
            'mobile' => [
                'string' => '请输入手机号码'
            ],
            'orderBy'  => [
                'in_list' => '排序类型只能是 username,login_time 中的一个'
            ]
        ];

        try {
            $this->getUser();

            if (!$this->validate($rules, $errorsMsg)) {
                $errors = $this->validator->getErrors();

                throw new Exception(array_shift($errors));
            }

            $query    = $this->validator->getValidated();
            $page     = intval($query["page"] ?? 1);
            $pageSize = intval($query["pageSize"] ?? 10);
        } catch (Exception $e) {
            return $this->responseMsg($e->getMessage());
        }

        $builder = db_connect()->table("user")->select("id, username, mobile, login_time, create_time");

        if (!empty($query["username"])) {
            $builder->like("username", $query["username"]);
        }

        if (!empty($query["mobile"])) {
            $builder->where("mobile", intval($query["mobile"]));
        }

        if (!empty($query["orderBy"])) {
            $builder->orderBy($query["orderBy"], "DESC");
        } else {
            $builder->orderBy("login_time", "DESC");
        }

        $countBuilder = clone $builder;
        $count        = $countBuilder->get()->getNumRows();
        $list         = $builder->get($pageSize, ($page - 1) * $pageSize);

        return $this->responseJson([
            "list"  => $list->getResultObject(),
            "total" => ceil($count / $pageSize),
            "count" => $count,
        ]);
    }
}